<template>
	<view class="login">
		<view class="login-dl">
			<text v-if="show">请登录</text>
			<text v-else>请注册</text>
		</view>
		<van-cell-group>
		  <van-field
		    :value="FromList.username"
		    required
		    clearable
		    label="用户名"
		    icon="question-o"
		    placeholder="请输入用户名"
			@change="handleValue('username', $event)"
		  />
		
		  <van-field
		    :value="FromList.password"
		    type="password"
		    label="密码"
		    placeholder="请输入密码"
		    required
		    border="false"
			@change="handleValue('password', $event)"
		  />
		</van-cell-group>
		<view class="box-bottom" v-if="show">
			<van-button plain type="primary" @click="lw(FromList)">登录</van-button>
			<text @click="show = false">去注册</text>
		</view>
		<view class="box-bottom" v-else>
			<van-button plain type="primary" @click="xhz(FromList)">注册</van-button>
			<text @click="show = true">去登录</text>
		</view>
	</view>
</template>

<script setup>
// vue3小程序生命周期函数
import { onShareAppMessage, onLoad, onShow, onHide } from '@dcloudio/uni-app';
import { reactive, toRefs } from 'vue'
import { postLogin,postreg } from '../../api/modules/login'
const state = reactive({
	FromList: {
		username:'',
		password:''
	},
	show: true
})
const handleValue = (key,e) => {
	const value = e.detail
	state.FromList[key] = value
}
// 登录
const lw = async (data) => {
	const res = await postLogin(data)
	if (res.message === '用户名或密码错误') {
		uni.showToast({
			title: res.message,
			icon: 'none',
			duration: 2000
		}) 
	} else if (res.message === '请输入用户名或密码') {
		uni.showToast({
			title: res.message,
			icon: 'none',
			duration: 2000
		}) 
	} else {
		uni.switchTab({ url: '/pages/my/my' })
		uni.setStorageSync('token',res.data)
		state.FromList = {}
	}
	
}
// 注册
const xhz = async (data) => {
	const { message } = await postreg(data)
	if (message === '用户名或密码错误') {
		uni.showToast({
			title: message,
			icon: 'none',
			duration: 2000
		}) 
	} else if (message === '请输入用户名或密码') {
		uni.showToast({
			title: message,
			icon: 'none',
			duration: 2000
		}) 
	} else {
		state.show = true
		state.FromList = {}
	}
}
// 页面加载
onLoad((message) => {
})

// 页面显示
onShow(() => {
	
})

// 页面隐藏
onHide(() => {
	
})

// 页面分享(不定义该函数 页面将无法分享)
onShareAppMessage(() => {
	
})
const { FromList,show } = toRefs(state)
</script>

<style lang="scss">
.login {
	.login-dl {
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		font-size: 30rpx;
		}
		.box-bottom {
			height: 60rpx;
			text-align: center;
			margin: 20rpx auto;
			text {
				display: inline-block;
				width: 100rpx;
				height: 100%;
				line-height: 60rpx;
			}
		}
}
</style>
